package controllers

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"strconv"
)

// var xxx = map[string]string{}

func ReadFile(filename string) (temp map[string]interface{}, err error) {
	// var temp map[string]string
	bytes, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Println("ReadFile: ", err.Error())
		return nil, err
	}

	if err := json.Unmarshal(bytes, &temp); err != nil {
		fmt.Println("Unmarshal: ", err.Error())
		// return nil, err
	}

	return temp, nil
}

func OutJson(userFile string, s map[string]interface{}) bool {
	b, err := json.Marshal(s)
	if err != nil {
		fmt.Println("json err:", err)
	}

	fout, err := os.Create(userFile)
	defer fout.Close()
	if err != nil {
		fmt.Println(userFile, err)
		return false
	}
	fout.WriteString(string(b))
	return true
}

func (this *MainController) Post() {
	award := this.GetString("awards")
	id := this.GetString("id")
	url := this.GetString("imgUrl")
	name := this.GetString("name")

	userFile := ".\\models\\data\\" + award + ".json"
	xxxMap, err := ReadFile(userFile)
	if err != nil {
		fmt.Println("readFile: ", err.Error())
		return
	}
	tKey := strconv.Itoa(len(xxxMap) + 1)
	fmt.Println(tKey)
	xxxMap[tKey] = map[string]string{"id": id, "award": award, "imgUrl": url, "name": name}

	OutJson(userFile, xxxMap)
	finishNum := strconv.Itoa(len(xxxMap))

	this.Data["json"] = map[string]interface{}{
		"success":   true,
		"message":   "success",
		"finishNum": finishNum,
		"award":     award,
		"id":        id,
		"name":      name}

	// pkgname := this.GetString("a")
	this.ServeJSON()
	return
}
